#include "WProgram.h"
#include "Tagger.h"

void Tagger::begin(uint8_t pinEmmiter,uint8_t pinReceiver, uint8_t pinMuzzleLed, Sound & sound){
  Tagger::sound = &sound;
  //tagger configuration right now it is the followig by default
  damage = 10;
  clipSize = 30;
  fireDelay = 19;
  startingClips = 7;
  reloadDelay = 100;
  nAmmo = clipSize; //assuming we start loaded this could change acording to the game
  muzzleLed = pinMuzzleLed;
  //all other initializations are made by the parent
  IRcommunication::begin(pinEmmiter,pinReceiver);
}

void Tagger::refreshStatus(){
	if((endShootMoment != 0) && (millis() > endShootMoment)){
		endShoot();
	}
}

void Tagger::startShoot(uint8_t team, uint8_t playerNumber){
  //Serial.println("BANG!");
  unsigned int message = 0;
  message = team << 13;
  message += playerNumber << 8;
  message += damage;

  send(message);
  digitalWrite(muzzleLed,HIGH);
  sound->shoot(); //TODO maybe the shoot sound should be inmediate to avoid a lag effect
  nAmmo--;
  endShootMoment = millis()+fireDelay;
}

void Tagger::endShoot(){
  digitalWrite(muzzleLed,LOW);
}

void Tagger::receive(){
  unsigned int message;

  //////HIT VARIABLES
  volatile uint8_t attackingTeam = 0;
  volatile uint8_t attackingPlayer = 0;
  volatile uint8_t attackingDamage = 0;

  message = IRcommunication::receive();
  if(message>0){
    if (!(message & 0xE000)) { //for hit messages the first value is 1
      //HIT
      attackingTeam = (message & 0xE000) >> 13;
      uint8_t attackingPlayer = (message & 0x1F00) >> 8;
      uint8_t attackingDamage = (message & 0x00FF);

      //como dagnamos al player des de tagger?
      //player.hurt(attackingDamage,attackingPlayer,attackingTeam);
    }
    else {
      //COMMAND
      //switch through the available command codes and play a
      //near miss as a default
    }
  }
  else {
    //something has activated the IR receiver but there was no message
    //we count it as a near miss
    sound->nearMiss();
    //mear miss
  }
}

